package com.gitee.hermer.boot.jee.ngrok.auto.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent;
import org.springframework.context.ApplicationListener;

import com.gitee.hermer.boot.jee.commons.dict.BootProperties;
import com.gitee.hermer.boot.jee.commons.utils.StringUtils;
import com.gitee.hermer.boot.jee.ngrok.NgrokClient;
import com.gitee.hermer.boot.jee.ngrok.Tunnel;
import com.gitee.hermer.boot.jee.ngrok.properties.NgrokProperties;

public class NgrokEmbeddedServletContainerInitializedEventListener implements
ApplicationListener<EmbeddedServletContainerInitializedEvent> {
	private final NgrokProperties ngrokProperties;

	public NgrokEmbeddedServletContainerInitializedEventListener(NgrokProperties ngrokProperties) {
		this.ngrokProperties = ngrokProperties;
	}

	@Autowired
	private BootProperties properties;
	
	@Override
	public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
		int port = event.getSource().getPort();
		String serverAddress = ngrokProperties.getServerAddress();
		try { 
			if(StringUtils.isEmpty(serverAddress) && properties != null){
				serverAddress = properties.getDictValueString("com.boot.jee.ngrok.serevr-address");
			}
		} catch (Exception e) { e.printStackTrace(); }
		int serverPort = ngrokProperties.getServerPort();
		String subdomain = ngrokProperties.getSubdomain();
		String hostname = ngrokProperties.getHostname();
		String proto = ngrokProperties.getProto();
		int remotePort = ngrokProperties.getRemotePort();
		String httpAuth = ngrokProperties.getHttpAuth();

		Tunnel tunnel = new Tunnel.TunnelBuild()
				.setPort(port)
				.setProto(proto)
				.setSubDomain(subdomain)
				.setHostname(hostname)
				.setRemotePort(remotePort)
				.setHttpAuth(httpAuth)
				.build();
		new NgrokClient(serverAddress, serverPort)
		.addTunnel(tunnel).start();
	}
}

